package com.bw.mine.model.service

import com.baweigame.xmpplibrary.XmppManager
import com.bw.mine.intent.LoginIntent
import com.bw.mine.model.api.UserCenterApi
import com.bw.mine.state.LoginState
import com.bw.mvicore.model.BaseModel
import com.bw.net.RetrofitUtils
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.consumeAsFlow

/**
 * @author:created by hahajing
 * 时间：2024/5/6 0006
 * 企鹅号:444511958
 * 描述:
 */
class LoginModel:BaseModel<LoginIntent>() {
    private val api:UserCenterApi by lazy {
        RetrofitUtils.create(UserCenterApi::class.java)
    }
    override fun handleIntent() {
        generateViewModelScope {
            intents.consumeAsFlow().collect{
                when(it){
                    is LoginIntent.FinalLoginIntent->{
                        login(it)
                    }
                }
            }
        }
    }

    private val _state:MutableStateFlow<LoginState> = MutableStateFlow(LoginState.LoginDefaultState)
    val state:MutableStateFlow<LoginState>
        get() = _state

    private suspend fun login(it: LoginIntent.FinalLoginIntent) {
        val result =  api.login(it.username,it.password)
        //登录xmpp服务器
        XmppManager.getInstance().xmppUserManager.login(it.username,it.password)
        if (result.code==0){
            _state.value = LoginState.LoginSuccessState(result.data)
        }else{
            _state.value = LoginState.LoginFailedState(IllegalStateException("登录失败，info:${result.msg}"))
        }
    }
}